﻿using System;

class LargestNumberViaBinSearch
{
    static void Main(string[] args)
    {
        //Exercise 4.
        //Write a program, that reads from the console an array of N integers and an integer K, sorts the array and using 
        //the method Array.BinSearch() finds the largest number in the array which is ≤ K.

        //Declare the array
        Console.Write("Enter the array length N: ");
        int n = int.Parse(Console.ReadLine());
        int[] array = new int[n];

        ////Initialize the array from the console
        //for (int i = 0; i < n; i++)
        //{
        //    Console.Write("Array [{0}]  ", i);
        //    array[i] = int.Parse(Console.ReadLine());
        //}

        //Initialize the array using random
        Random random = new Random();
        for (int i = 0; i < n; i++)
        {
            array[i] = random.Next(0, 100);
            Console.Write(array[i] + " ");        //print the array on the console
        }
        Console.WriteLine();        

        Console.Write("Enter an integer K: ");
        int k = int.Parse(Console.ReadLine());

        Array.Sort(array);
        Console.Write("The sorted array is:  ");
        for (int i = 0; i < n; i++)             //print the sorted array
        {
            Console.Write(array[i] + " ");        
        }
        Console.WriteLine();

        int index = Array.BinarySearch(array, k);

        if (index < -1)
        {
            Console.WriteLine("The largest number in the array which is smaller or equal to {0} is:  {1}", k, array[~index - 1]);
        }
        else if (~index == 0)
        {
            Console.WriteLine("There is no such number.");
        }
        else
        {
            Console.WriteLine("The largest number in the array which is smaller or equal to {0} is:  {1}", k, array[index]);
        }
    }
}

